﻿using CKS.Core.Framework;
using FreeSql;
using Google.Protobuf.WellKnownTypes;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Channels;
using System.Threading.Tasks;
using ZR.Model.Models.ProductionControl;

namespace CKS.PLC.Action.Subscription {

    /// <summary>
    /// 曲线数据采集订阅点<para/>
    /// 散热片OP60站压力温度曲线数据采集<para/>
    /// </summary>
    [SubscribeAction("CurveDataSubscribe")]
    public class CurveDataAction : SubscribeBase {

        private static List<CollectItem> CollectItems = new List<CollectItem>();
        private const int _interval = 5; //时间间隔，单位秒

        public CurveDataAction(DecodeValue decodeValue) : base(decodeValue) {


        }


        public override void ExecuteAction(Dictionary<string, object> execParams) {

            using (var ObjectCo = base.FreeSql.Ado.MasterPool.Get())
            {
                //db
                var conn = ObjectCo.Value;
                //点位值
                var result = DecodeValue.Value as List<bool>;
                //点位信息
                var postionData = DecodeValue.Position;

                var collectItem = CollectItems.Where(o => o.PlcID == postionData.PlcId && o.DbBlock == postionData.BlockDb).LastOrDefault();
                
                if (collectItem == null)
                {
                    CollectItems.Add(new CollectItem() { PlcID = postionData.PlcId, DbBlock = postionData.BlockDb, StartTime = DateTime.Now });

                }
                else if (collectItem != null && (DateTime.Now - collectItem.StartTime).TotalSeconds < _interval)  //判断时间间隔是否小于5s，小于5s则跳过
                {
                    return;
                }
                else if (collectItem != null) //重新计时
                {
                    collectItem.StartTime = DateTime.Now;
                }
                
                //WriteLogUI($"工站：{postionData.PlcId}-{postionData.WorkStationCode}，DB块：{postionData.BlockDb}，点位：{postionData.BytePosition}，ActionType：{postionData.EffectType.ToString()}，ActionKey：{postionData.ActionKey}");

                List<CksCollectedCurveData> curveList = new List<CksCollectedCurveData>();
                for (int i = 0; i < result.Count; i++)
                {
                    //获取当前word 中 当前 bit位的数据
                    if (result[i])
                    {
                        var curPressureChannelP = DecodeValue.GetPositionByActionKey(postionData, $"PressureChannel{i + 1}");
                        var pressureChannelValue = DecodeValue.GetLinkDecodeObject(curPressureChannelP).Value.ToString();
                        var curTemperatureChannelP = DecodeValue.GetPositionByActionKey(postionData, $"TemperatureChannel{i + 1}");
                        var temperatureChannelValue = DecodeValue.GetLinkDecodeObject(curTemperatureChannelP).Value.ToString();

                        //数据采集逻辑
                        var curveData = new
                        {
                            PrimaryCode = base.GetMainCodeValue(),
                            Channel = i + 1,
                            PressureChannel = pressureChannelValue,
                            TemperatureChannel = temperatureChannelValue,
                            CreateTime = DateTime.Now
                        };

                        var cksCollectedCurveData = new CksCollectedCurveData
                        {
                            PlcId = postionData.PlcId,
                            DbBlock = postionData.BlockDb,
                            PrimaryCode = curveData.PrimaryCode,
                            CurveData = JsonConvert.SerializeObject(curveData),
                            CreateTime = curveData.CreateTime,
                        };
                        curveList.Add(cksCollectedCurveData);
                        WriteLogUI($"{postionData.BlockDb}，采集通道{i + 1}，压力数据: {curveData.PressureChannel}，温度数据: {curveData.TemperatureChannel}");
                    }
                }

                if (curveList.Count > 0)
                {
                    var affrows = conn.Insert(curveList).ExecuteAffrows();
                    WriteLogUI($"{postionData.BlockDb}，affrows：{affrows}");
                }

            }
        }

    }


    public class CollectItem {

        public int PlcID { get; set; }

        public int DbBlock { get; set; }

        public DateTime StartTime { get; set; }

    }

}
